package com.stylefeng.guns.modular.apple_id_manage.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.util.CmdUtil;
import com.stylefeng.guns.modular.apple.utils.ExcelUtil;
import com.stylefeng.guns.modular.apple.utils.TimeUtil;
import com.stylefeng.guns.modular.apple.vo.Paging;
import com.stylefeng.guns.modular.apple_id_manage.model.AppleIds;
import com.stylefeng.guns.modular.apple_id_manage.dao.AppleIdsMapper;
import com.stylefeng.guns.modular.apple_id_manage.service.IAppleIdsService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.apple_sign_task_manage.dao.SignTasksMapper;
import com.stylefeng.guns.modular.apple_sign_task_manage.service.ISignTasksService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 苹果账号表 服务实现类
 * </p>
 *
 * @author godrui
 * @since 2020-06-20
 */
@Service
public class AppleIdsServiceImpl extends ServiceImpl<AppleIdsMapper, AppleIds> implements IAppleIdsService {
    private static final Logger logger = LoggerFactory.getLogger(AppleIdsServiceImpl.class);

    @Resource
    private SignTasksMapper signTasksMapper;

    @Override
    @Transactional
    public void importExcelOfAppleID(MultipartFile file) {
        try {
            List<Map<Integer,String>> readList =  ExcelUtil.readExcelData(file);
            if (readList.size() == 0){
                throw new GunsException(BizExceptionEnum.APPLE_EXCEL_IMPORT_FAIL);
            }
            List<AppleIds> appleIdsList = new ArrayList<>();
            readList.forEach(r->{
                appleIdsList.add(AppleIds.builder()
                        .account(r.get(0))
                        .password(r.get(1))
                        .usedDeviceCount(Integer.parseInt(r.get(2)))
                        .leftDeviceCount(Integer.parseInt(r.get(3)))
                        .importDate(new Date())
                        .build());
                String str = "security add-internet-password -a "+r.get(0)+" -s deliver."+r.get(0)+" -w "+r.get(1);
                logger.info("运行cmd命令：{}",str);
                String flag = CmdUtil.cmd(str);
                logger.info("cmd run flag: {}", flag);
            });
            this.baseMapper.insertForEach(appleIdsList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public void changeStatus(Integer appId, Integer status) {
        AppleIds appleIds = this.selectById(appId);
        appleIds.setStatus(status);
        if (status == 1){
            appleIds.setBlockedDate(new Date());
        }
        this.updateById(appleIds);

        signTasksMapper.updateSignStatus(appleIds.getAccount(),4);
    }

    /**
     * 获取可用账号数量
     * @return
     */
    @Override
    public Integer getEnableUseCount() {
        return this.baseMapper.findEnableDeviceCount();
    }

    /**
     * 导出表格
     * @param type 1-未使用账号，2-已使用账号，3-已封账号
     * @param month
     */
    @Override
    public void exportExcel(HttpServletResponse response,Integer type, String month) {
        EntityWrapper<AppleIds> wrapper = new EntityWrapper<>();
        String sheetName = "苹果账号使用详情";
        if (type == 1){
            //查询未使用的账号排序
            sheetName = "未使用账号详情";
            wrapper.eq("status",0);
            wrapper.ne("used_device_count",100);
            wrapper.orderBy(true,"status");
        }else if(type == 2){
            //查询已使用列表
            sheetName = "已使用账号详情";
            wrapper.where("(" +
                    "(used_device_count={0} and status = 0)" +
                    "or " +
                    " ((status = 1 or status=3) and DATE_FORMAT(blocked_date,'%Y-%m-%d') > DATE_FORMAT(NOW(),'%Y-%m-%d')))" +
                    " and DATE_FORMAT(import_date,'%Y-%m') = {1}",100,month);
            wrapper.orderBy(false,"used_device_count");
        }else{
            //查询被封账号列表
            sheetName = "已封账号详情";
            wrapper.where("(status = 1 or status=3)" +
                    " and DATE_FORMAT(blocked_date,'%Y-%m-%d') <= DATE_FORMAT(NOW(),'%Y-%m-%d')" +
                    " and DATE_FORMAT(blocked_date,'%Y-%m') = {0}",month);
        }
        List<AppleIds> idsList = this.selectList(wrapper);

        HSSFWorkbook workbook = new HSSFWorkbook();
        //1、创建一个Excel表单，参数为sheet的名字
        HSSFSheet sheet = workbook.createSheet(sheetName);
        //生成表头集合
        List<String> colList = new ArrayList<>();
        colList.add("账号");
        colList.add("已用设备数量");
        colList.add("剩余设备数量");
        colList.add("有效期");
        colList.add("导入时间");
        if(type == 3){
            colList.add("被封时间");
            colList.add("状态");
        }else{
            colList.add("状态");
        }
        //2、创建表头
        ExcelUtil.setTableHeader(workbook,sheet,colList);
        //3、插入内容数据
        int rowNum = 1;
        for (AppleIds appleId: idsList){
            HSSFRow row = sheet.createRow(rowNum);
            row.createCell(0).setCellValue(appleId.getAccount());
            row.createCell(1).setCellValue(appleId.getUsedDeviceCount());
            row.createCell(2).setCellValue(appleId.getLeftDeviceCount());
            row.createCell(3).setCellValue(TimeUtil.formatDate(appleId.getValidDate(),"yyyy-MM-dd"));
            row.createCell(4).setCellValue(TimeUtil.formatDate(appleId.getImportDate(),"yyyy-MM-dd"));
            if (type == 3){
                row.createCell(5).setCellValue(TimeUtil.formatDate(appleId.getBlockedDate(),"yyyy-MM-dd"));
                row.createCell(6).setCellValue("已封");
            }else{
                row.createCell(5).setCellValue("正常");
            }
            rowNum++;
        }
        String fileName = "AppleIdDetail"+System.currentTimeMillis()+".xls";
        //写入文件并将文件已二进制流的方式返回为调用者
        ExcelUtil.writeWorkBook(response,workbook,fileName);
        //4、写入文件并将文件已二进制流的方式返回为调用者
    }

    @Override
    public Object appleIdList(int type, Integer page, Integer limit) {
        int start = (page>0?page-1:page) * limit;
        Paging<AppleIds> paging = new Paging<>();

        if (type == 0){
            //未使用账号列表
            Integer total = this.baseMapper.findUnUsedCount();
            paging.setTotal(total.longValue());
            paging.setItems(this.baseMapper.findUnUsedAccount(start,limit));
        }else if(type == 1){
            //已使用账号列表
            Integer total = this.baseMapper.findUsedCount();
            paging.setTotal(total.longValue());
            paging.setItems(this.baseMapper.findUsedAccount(start,limit));
        }else{
            //已被封账号列表
            Integer total = this.baseMapper.findBlockedCount();
            paging.setTotal(total.longValue());
            paging.setItems(this.baseMapper.findBlockedAccount(start,limit));
        }
        return paging;
    }
}
